package com.mediatek.factorymode.sdcard;

import com.mediatek.factorymode.R;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.os.storage.DiskInfo;
import android.os.storage.StorageManager;
import android.os.storage.VolumeInfo;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.mediatek.factorymode.Utils;
import java.io.File;
import java.util.List;

public class SDCard extends Activity
  implements View.OnClickListener
{
  private Button mBtFailed;
  private Button mBtOk;
  private TextView mInfo;
  private SharedPreferences mSp;
  // chenxs: detect external sdcard 20180316 @{
  private StorageManager mStorageManager = null;
  public static final String UNIT_B = "B";
  public static final String UNIT_KB = "KB";
  public static final String UNIT_MB = "MB";
  public static final String UNIT_GB = "GB";
  public static final String UNIT_TB = "TB";
  private static final int UNIT_INTERVAL = 1024;
  private static final double ROUNDING_OFF = 0.005;
  private static final int DECIMAL_NUMBER = 100;
  // chenxs @}

  // chenxs: detect external sdcard 20180316 @{
  private File getFile() {
    mStorageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
    List<VolumeInfo> volumeInfoList = mStorageManager.getVolumes();
    if (volumeInfoList != null) {
      for (VolumeInfo vi : volumeInfoList) {
        DiskInfo diskInfo = vi.getDisk();
        if (diskInfo != null && diskInfo.isSd()) {
          String sdcardState = vi.getEnvironmentForState(vi.getState());
          if (Environment.MEDIA_MOUNTED.equals(sdcardState)) {
            return vi.getPath();
          }
        }
      }
    }
    return null;
  }

  public static String sizeToString(long size) {
      String unit = UNIT_B;
      if (size < DECIMAL_NUMBER) {
          return Long.toString(size) + " " + unit;
      }

      unit = UNIT_KB;
      double sizeDouble = (double) size / (double) UNIT_INTERVAL;
      if (sizeDouble > UNIT_INTERVAL) {
          sizeDouble = (double) sizeDouble / (double) UNIT_INTERVAL;
          unit = UNIT_MB;
      }
      if (sizeDouble > UNIT_INTERVAL) {
          sizeDouble = (double) sizeDouble / (double) UNIT_INTERVAL;
          unit = UNIT_GB;
      }
      if (sizeDouble > UNIT_INTERVAL) {
          sizeDouble = (double) sizeDouble / (double) UNIT_INTERVAL;
          unit = UNIT_TB;
      }

      // Add 0.005 for rounding-off.
      long sizeInt = (long) ((sizeDouble + ROUNDING_OFF) * DECIMAL_NUMBER); // strict to two
      // decimal places
      double formatedSize = ((double) sizeInt) / DECIMAL_NUMBER;

      if (formatedSize == 0) {
          return "0" + " " + unit;
      } else {
          return Double.toString(formatedSize) + " " + unit;
      }
  }
  // chenxs @}

  public void SDCardSizeTest()
  {
      StringBuilder localStringBuilder = new StringBuilder();
      try{ // tongjun  Add begin
          // chenxs: detect external sdcard 20180316 @{
          //StatFs localStatFs = new StatFs("/mnt/m_external_sd");///mnt/sdcard
          //long l1 = localStatFs.getBlockCount();
          //if(l1 == 0){
          //    localStringBuilder.append(this.getString(R.string.sdcard_tips_failed));
          //}else{
          //    long l2 = localStatFs.getBlockSize();
          //    long l3 = localStatFs.getAvailableBlocks();
          //    long l4 = l1 * l2 / 1024L / 1024L;
          //    long l5 = l3 * l2 / 1024L / 1024L;
          //    localStringBuilder.append(this.getString(R.string.sdcard_tips_success)).append("\n\n");
          //    localStringBuilder.append(this.getString(R.string.sdcard_totalsize)).append(l4).append("MB").append("\n\n");
          //    localStringBuilder.append(this.getString(R.string.sdcard_freesize)).append(l5).append("MB").append("\n\n");
          //}
        File file = getFile();
        if (file != null) {
          long freeSpace = file.getUsableSpace();
          long totalSpace = file.getTotalSpace();

          localStringBuilder.append(this.getString(R.string.sdcard_tips_success)).append("\n\n");
          localStringBuilder.append(this.getString(R.string.sdcard_totalsize)).append(sizeToString(totalSpace)).append("\n\n");
          localStringBuilder.append(this.getString(R.string.sdcard_freesize)).append(sizeToString(freeSpace)).append("\n\n");
        } else {
          localStringBuilder.append(this.getString(R.string.sdcard_tips_failed));
        }
        // chenxs @}
      }catch(Exception e){
        localStringBuilder.append(this.getString(R.string.sdcard_tips_failed));
      }// tongjun  Add end
      this.mInfo.setText(localStringBuilder.toString());
  }

  public void onClick(View paramView)
  {
    SharedPreferences localSharedPreferences = this.mSp;
    if(paramView.getId() == this.mBtOk.getId()){
        Utils.SetPreferences(this, localSharedPreferences, R.string.sdcard_name, "success");
        finish();
    }
    else{
        Utils.SetPreferences(this, localSharedPreferences, R.string.sdcard_name, "failed");
        finish();
    }
  }

  BroadcastReceiver mMediaMountReceiver = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
          String action = intent.getAction();
          String mountPoint = null;
          Uri mountPointUri = intent.getData();
          if (mountPointUri != null) {
              mountPoint = mountPointUri.getPath();
          }

          if (mountPoint == null || mountPointUri == null) {
              return;
          }

          SDCardSizeTest();
      }
  };

  @Override
  public void onCreate(Bundle paramBundle)
  {
    super.onCreate(paramBundle);
    setContentView(R.layout.sdcard);
    SharedPreferences localSharedPreferences = getSharedPreferences("FactoryMode", 0);
    this.mSp = localSharedPreferences;
    TextView localTextView = (TextView)findViewById(R.id.sdcard_info);
    this.mInfo = localTextView;
    this.mBtOk = (Button)findViewById(R.id.bt_ok);
    this.mBtOk.setOnClickListener(this);
    this.mBtFailed = (Button)findViewById(R.id.bt_failed);
    this.mBtFailed.setOnClickListener(this);
    SDCardSizeTest();

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
    intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
    intentFilter.addAction(Intent.ACTION_MEDIA_EJECT);
    intentFilter.addDataScheme("file");
    registerReceiver(mMediaMountReceiver, intentFilter);
  }

  @Override
  public void onDestroy() {
    unregisterReceiver(mMediaMountReceiver);
    super.onDestroy();
  }
}